﻿using CYZH.CommandAssembly.JsonObject;
using CYZH.Common;
using CYZH.Service.Drought;
using SuperWebSocket;
using SuperWebSocket.SubProtocol;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CYZH.CommandAssembly.Command
{
    public class Merge : JsonSubCommand<MergeParam>
    {
        protected override void ExecuteJsonCommand(WebSocketSession session, MergeParam commandInfo)
        {
            double[] ext = { 0, 0, 0, 0 };
            OutRasterConfigElement rce = Common.ConfigHelper.GetConfigParamByXzqhCode(commandInfo.XzqhCode);

            string strminx = rce.Extents;
            string[] strext = strminx.Split(',');

            double MinX = Convert.ToDouble(strext[0]);
            double MinY = Convert.ToDouble(strext[1]);
            double MaxX = Convert.ToDouble(strext[2]);
            double MaxY = Convert.ToDouble(strext[3]);
            ext[0] = MinX;// { MinX, MinY, MaxX, MaxY };
            ext[1] = MinY;
            ext[2] = MaxX;
            ext[3] = MaxY;

            string aoifile = rce.ShpFile;
            string cldaoiFile = rce.ChildShpFile;
            string layername = commandInfo.XzqhCode + "_" + commandInfo.FileTime + "_"+commandInfo.Algorithm.ToLower();
            string strextents = ext[0] + ", " + ext[1] + ", " + ext[2] + ", " + ext[3];



            //string ftype = "";
            //if (commandInfo.Algorithm.Equals("SPI"))
            //{
            //    ftype = "ASC";
            //}
            //if (commandInfo.Algorithm.Equals("NDVI") || commandInfo.Algorithm.Equals("GRASS") || commandInfo.Algorithm.Equals("CVI"))
            //{
            //    ftype = "MOD09Q1";
            //}
            //if (commandInfo.Algorithm.Equals("LST") || commandInfo.Algorithm.Equals("TVDI"))
            //{
            //    ftype = "MOD11A1";
            //}
            //if (commandInfo.Algorithm.Equals("GRASS"))
            //{
            //    ftype = "MOD09Q1";
            //}

            string smouth = "", sdays = "", sxun = "", stype = "";
            if (commandInfo.FileTime.Length == 4)//2013
            {
                stype = "year";
            }
            if (commandInfo.FileTime.Length == 6)//201304
            {
                smouth = commandInfo.FileTime.Substring(4);
                stype = "mouth";
            }
            if (commandInfo.FileTime.Length == 8)//20130401
            {
                smouth = commandInfo.FileTime.Substring(4, 2);
                sxun = commandInfo.FileTime.Substring(6);
                stype = "xun";
            }

            //查询数据是否已经做过
            List<ModisResultBean> res = CommonService.queryRasterResult(commandInfo.XzqhCode, commandInfo.FileTime, commandInfo.Algorithm, stype, commandInfo.MergeType);
            if (res.Count != 0)
            {
                //string filename = res[0].FileName;
                //string filepath = FileOper.GetExitsModisFilePath(ftype, filename, commandInfo.Algorithm, "map");
                //string unixfile1 = filepath.Replace('\\', '/');
                MapFileResult resultstate6 = new MapFileResult();
                resultstate6.process = "100";
                resultstate6.state = "0";
                resultstate6.value = "success";
                resultstate6.LayerName = res[0].LayerName;
                resultstate6.Extents = strextents;
                //resultstate6.MapFile = unixfile1;
                SendJsonMessage(session, resultstate6);
                Logger.Singleton.Debug(String.Format("结果已经存在."));
                return;
            }

            ResultState resultstate0 = new ResultState();
            resultstate0.process = "30";
            resultstate0.value = "正在生成数据...";
            SendJsonMessage(session, resultstate0);


            List<string> files = new List<string>();
            foreach (string filename in commandInfo.MODISFileList)
            {
                string filepath = FileOper.GetExitsModisFilePath(filename , commandInfo.Algorithm);

                if (!File.Exists(filepath))
                {
                    continue;
                }
                files.Add(filepath);
            }

            ResultState resultstate1 = new ResultState();
            resultstate1.process = "50";
            resultstate1.value = "正在合并...";
            SendJsonMessage(session, resultstate1);


            string aoiShpFile = FileOper.GenAOIFilePath(aoifile);
            string cldaoiShpFile = FileOper.GenAOIFilePath(cldaoiFile);  
            string sfilename = FileOper.GenModisFilePath( layername, commandInfo.Algorithm);

            MergeService ms = new MergeService();
            int rst = ms.Merge(files, commandInfo.MergeType, aoiShpFile, sfilename);
            if (rst != 0)
            {
                ResultState errstate = new ResultState();
                errstate.process = "100";
                errstate.state = "-1";
                errstate.value = "数据合并出错!";
                SendJsonMessage(session, errstate);
                return;
            }
            //生成map文件
            string mapfile = MapFileUtils.GenMapFile( commandInfo.Algorithm, strextents.Replace(',', ' '), layername);
            //生成统计信息，按当前行政区划的下一级统计
            string str_static = CommonService.RegionaStatistics(sfilename, cldaoiShpFile);
            //保存到数据库
            CommonService.saveRasterResult(mapfile, commandInfo.FileTime, commandInfo.XzqhCode, layername, commandInfo.Algorithm, smouth, sdays, sxun, stype, str_static,commandInfo.MergeType);

            //string unixfile = mapfile.Replace('\\', '/');
            MapFileResult resultstate2 = new MapFileResult();
            resultstate2.process = "100";
            resultstate2.state = "0";
            resultstate2.value = "success";
            resultstate2.LayerName = layername;
            resultstate2.Extents = strextents;
            //resultstate2.MapFile = unixfile;
            SendJsonMessage(session, resultstate2);
            Logger.Singleton.Debug(String.Format("数据合并结束，生成MAP文件路径：{0}.", mapfile));

        }
    }
}
